package com.carambatv.android.ui.feed;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xml.sax.SAXException;

import android.content.ContentProviderOperation;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.carambatv.android.R;
import com.carambatv.android.adapter.RssAdapter;
import com.carambatv.android.db.CarambaDBSchema;
import com.carambatv.android.db.RssColumns;
import com.carambatv.android.db.RssQuery;
import com.carambatv.android.model.RssObject;
import com.carambatv.android.rss.RssFeed;
import com.carambatv.android.rss.RssItem;
import com.carambatv.android.rss.RssReader;
import com.carambatv.android.utils.DialogManager;

public class FeedFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
	public static final int FEED = 123;
	private CursorAdapter mAdapter;
	private ListView mList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View root = inflater.inflate(R.layout.feed_container, container, false);
		mList = (ListView) root.findViewById(R.id.rss_list);
		return root;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		new UpdateRss().execute();

		mAdapter = new RssAdapter(getActivity(), null);
		mList.setAdapter(mAdapter);
		mList.setOnItemClickListener(this);

		getActivity().getSupportLoaderManager().initLoader(FEED, Bundle.EMPTY, this);

	}

	@Override
	public Loader<Cursor> onCreateLoader(int token, Bundle bundle) {
		return new CursorLoader(getActivity(), RssObject.CONTENT_URI, RssQuery.PROJECTION, null, null, RssObject.DATE_SORT);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> lader, Cursor newCursor) {
		mAdapter.swapCursor(newCursor);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mAdapter.swapCursor(null);
	}

	public class UpdateRss extends AsyncTask<Void, Void, ArrayList<RssItem>> {

		@Override
		protected ArrayList<RssItem> doInBackground(Void... params) {
			URL url;
			ArrayList<RssItem> rssItems = null;
			try {
				url = new URL("http://carambatv.ru/feed");
				RssFeed feed = RssReader.read(url);
				rssItems = feed.getRssItems();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

			return rssItems;
		}

		@Override
		protected void onPostExecute(ArrayList<RssItem> result) {
			super.onPostExecute(result);
			if (result != null) {
				ArrayList<ContentProviderOperation> insertOperations = new ArrayList<ContentProviderOperation>();
				for (RssItem rssItem : result) {
					insertOperations.add(ContentProviderOperation.newInsert(RssObject.CONTENT_URI).withValue(RssColumns.TITLE.getName(), rssItem.getTitle())
							.withValue(RssColumns.LINK.getName(), rssItem.getLink()).withValue(RssColumns.PUBDATE.getName(), rssItem.getPubDate().getTime()).build());
				}
				try {
					if (getActivity() != null) {
						getActivity().getContentResolver().applyBatch(CarambaDBSchema.CONTENT_AUTHORITY, insertOperations);
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				} catch (OperationApplicationException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		RssAdapter adapter = (RssAdapter) adapterView.getAdapter();
		Cursor cursor = adapter.getCursor();

		if (cursor != null && cursor.moveToPosition(position)) {
			String link = cursor.getString(RssQuery.LINK);
			new CarambaParser(getActivity()).execute(link);

		}
	}

	public class CarambaParser extends AsyncTask<String, Void, String> {
		private FragmentActivity context;

		public CarambaParser(FragmentActivity fragmentActivity) {
			this.context = fragmentActivity;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			DialogManager.showDialog(context);

		}

		@Override
		protected String doInBackground(String... params) {
			String id_video = null;
			URL url = null;
			Document doc = null;
			try {
				url = new URL(params[0]);
				doc = (Document) Jsoup.parse(url, 10 * 1000);
				Elements items = doc.getElementsByTag("iframe");
				Element item = items.get(0);
				String linkHref = item.attr("src");
				StringTokenizer st = new StringTokenizer(linkHref, "/");
				while (st.hasMoreTokens()) {
					id_video = st.nextToken();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			return id_video;
		}

		@Override
		protected void onPostExecute(String id_video) {
			super.onPostExecute(id_video);
			DialogManager.hideDialog();
			try {
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + id_video));
				startActivity(intent);
			} catch (Exception e) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse("market://details?id=com.google.android.youtube"));
				try {
					startActivity(intent);
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}

		}

	}

}
